package com.b2b2c.conf;

import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.b2b2c.until.Config;

/**
 * 单库配置
 * @author Administrator
 */
public class MybatisSingleConf {

	private Config env = Config.getInstance("db");

	/**
	 * 创建数据源(数据源的名称：方法名可以取为XXXDataSource(),XXX为数据库名称,该名称也就是数据源的名称)
	 */
	public DataSource singleDbDataSource() {
		Properties props = new Properties();
		
		Map<String, String> map = env.getConfig();
		
		props.put("driverClassName", map.get("spring.datasource.single.driverClassName"));
		props.put("url", map.get("spring.datasource.single.url"));
		props.put("username", map.get("spring.datasource.single.username"));
		props.put("password", map.get("spring.datasource.single.password"));
		try {
			return DruidDataSourceFactory.createDataSource(props);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		
		return null;
	}
	
	 /**
	      * 根据数据源创建SqlSessionFactory
      */
    public SqlSessionFactory sqlSessionFactory(DataSource ds) {
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(ds);// 指定数据源(这个必须有，否则报错)
        
        Map<String, String> map = env.getConfig();
        
        fb.setTypeAliasesPackage(map.get("mybatis.single.typeAliasesPackage"));
        // 下边两句仅仅用于*.xml文件，如果整个持久层操作不需要使用到xml文件的话（只用注解就可以搞定），则不加
        try {
			fb.setMapperLocations(
			        new PathMatchingResourcePatternResolver().getResources(map.get("mybatis.single.mapper-locations")));
			return fb.getObject();
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        return null;
    }

    /**
     * 	配置事务管理器
     */
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
